
from datetime import datetime

from flask import current_app, jsonify
from flask import g
from flask import request

from info import constants
from info.models import House, Area, Order
from info.utils.common import user_login
from info.utils.response_code import RET
from flask import send_file
from info.utils.response_code import RET
from info.models import House
from info.modules.list import house_blu_list


@house_blu_list.route('/api/v1.0/houses')
def house_list_blu():
    start_date = request.args.get("sd")  # 用户入住日期
    end_date = request.args.get("ed")  # 用户离开日期
    area_id = request.args.get("aid")  # 入住区县
    sort_key = request.args.get("sk", "new")  # 排序关键字,当未选择排序条件时，默认按最新排序，这个new关键字根据前端定义走的
    page = request.args.get("p")  # 页数
    try:
        if start_date:
            start_date = datetime.strptime(start_date, "%Y-%m-%d")

        if end_date:
            end_date = datetime.strptime(end_date, "%Y-%m-%d")
        # 当用户两者都选择情况下，需要进行判断，入住日期肯定是小于或等于离开日期的
        if start_date and end_date:
            assert start_date <= end_date
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="日期参数有误")

    try:
        page = int(page)
    except Exception as e:
        # 如果出现异常则使page=1
        page = 1
        current_app.logger.error(e)

    if area_id:
        try:
            area = Area.query.get(area_id)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="数据库查询失败")
        if not area:
            data={
                "total_page": 0
            }
            return jsonify(errno=RET.NODATA, errmsg="没有该地区房源",data=data)

    filter_params = []
    conflict_orders = None
    try:
        if start_date and end_date:
            # 查询冲突的订单所有对象
            conflict_orders = Order.query.filter(Order.begin_date <= end_date, Order.end_date >= start_date).all()
        elif start_date:
            # 用户只选择入住日期
            conflict_orders = Order.query.filter(Order.end_date >= start_date).all()
        elif end_date:
            # 用户只选择离开日期
            conflict_orders = Order.query.filter(Order.begin_date <= end_date).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库异常")

    if conflict_orders:
        # 从订单中获取冲突的房屋id
        conflict_house_ids = [order.house_id for order in conflict_orders]
        # 如果冲突的房屋id不为空，向查询参数中添加条件
        # if conflict_house_ids:
        filter_params.append(House.id.notin_(conflict_house_ids))
    if area_id:
        filter_params.append(House.area_id == area_id)

    if sort_key == "booking":  # 入住做多
        house_query = House.query.filter(*filter_params).order_by(House.order_count.desc())
    elif sort_key == "price-inc":  # 价格低-高
        house_query = House.query.filter(*filter_params).order_by(House.price.asc())
    elif sort_key == "price-des":  # 价格高-低
        house_query = House.query.filter(*filter_params).order_by(House.price.desc())
    else:
        # 如果用户什么都没选择，则按照最新排序（数据库字段创建时间）
        house_query = House.query.filter(*filter_params).order_by(House.create_time.desc())

    house_list = []
    total_page = 0
    current_page = 1
    try:
        page_obj = house_query.paginate(page=page, per_page=constants.HOME_PAGE_MAX_NEWS, error_out=False)
        house_list = page_obj.items
        total_page = page_obj.pages
        current_page = page_obj.page
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库异常")

    houses = [house.to_basic_dict() for house in house_list]

    data={
        "houses": houses,
        "total_page": total_page,
        "current_page": current_page
    }

    return jsonify(errno=RET.OK, errmsg="OK",data=data)



@house_blu_list.route("/detail")
def detail():
    return send_file("static/html/detail.html")


@house_blu_list.route("/api/v1.0/houses/<int:house_id>")
@user_login
def index(house_id):
    # house_id = request.args.get("id")
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    try:
        house = House.query.filter_by(id=house_id).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, error="数据库查询错误")

    data = {
        "house":house.to_full_dict() if house else None,
        "user_id":user.id
    }

    return jsonify(data=data, errmsg="成功", errno=RET.OK)


